<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>TMDb</title>
  <link href="//vjs.zencdn.net/7.11.4/video-js.min.css" rel="stylesheet">
  <script src="//vjs.zencdn.net/7.11.4/video.min.js"></script>
  <style>
    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0, 0, 0, 0.4);
    }


    .modal-content {
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 60%;
      background-color: #fefefe;
      position: relative;
      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
      animation-name: modalopen;
      animation-duration: 0.4s;
    }

    .close {
      color: #aaa;
      position: absolute;
      right: 25px;
      top: 0;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }

    @keyframes modalopen {
      from {
        opacity: 0
      }

      to {
        opacity: 1
      }
    }
  </style>
</head>


<body>
<div th:each="movie : ${movies}">
  <h2 th:text="${movie.getTitle()}"></h2>
  <img th:src="'https://image.tmdb.org/t/p/w500' + ${movie.getPosterPath()}" th:data-src="'https://image.tmdb.org/t/p/w780/${movie.getPosterPath()}" th:data-video="${movie.getVideoKey()}"
       th:alt="${movie.getTitle()}" class="thumbnail" />


</div>

<div id="myModal" class="modal">
  <div class="modal-content">
    <span class="close">&times;</span>
    <video id="video-player" class="video-js vjs-default-skin"></video>
  </div>
</div>

<script>
  const modal = document.getElementById("myModal");
  const span = document.getElementsByClassName("close")[0];
  const videoPlayer = videojs('video-player');

  document.querySelectorAll('.thumbnail').forEach((thumb) => {
    thumb.addEventListener('click', function () {
      const videoUrl = 'https://www.youtube.com/watch?v=' + this.dataset.video;
      videoPlayer.src({
        src: videoUrl,
        type: 'video/youtube'
      });
      modal.style.display = "block";
      videoPlayer.play();
    });
  });

  span.onclick = function () {
    videoPlayer.pause();
    modal.style.display = "none";
  }

  window.onclick = function (event) {
    if (event.target == modal) {
      videoPlayer.pause();
      modal.style.display = "none";
    }
  }
</script>
</body>
</html>